package mobi.pfff.rest.resource;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import mobi.pfff.rest.bean.User;

/**
 * 用户 resource 
 * @date 2015年1月5日 下午2:49:42
 * @author pfff
 */
@Path("/users")
public class UserResource {

	private static Map<String, User> userMap = new HashMap<String, User>(); // 存储用户
	
	/**
	 * @return xml格式的数据
	 */
	/*@GET
	@Produces(MediaType.APPLICATION_XML)
	public List<User> getAllUser () {
		
		List<User> users = new ArrayList<User>();
		User u1 = new User("001", "Pfff", "23");
		User u2 = new User("002", "Jason", "32");
		User u3 = new User("003", "Tom", "29");
		
		userMap.put(u1.getUserId(), u1);
		userMap.put(u2.getUserId(), u2);
		userMap.put(u3.getUserId(), u3);
		
		users.addAll(userMap.values());
		
		return users;
	}
	
	@GET
	@Path("/getUserXml")
	@Produces(MediaType.APPLICATION_XML)
	public User getUserXml() {
		
		User user = new User();
		user.setUserId("004");
		user.setUserName("Amand");
		user.setAge("21");
		return user;
	}
	
	@GET
	@Path("/getUserJson")
	@Produces(MediaType.APPLICATION_JSON)
	public User getUserJson() {
		
		User user = new User();
		user.setUserId("005");
		user.setUserName("Snow");
		user.setAge("28");
		return user;
	}
	*/
	/**
	 *  模拟CRUD操作
	 */
	
	/**
	 * 增加
	 * @param User
	 */
	
	// Consumes 用于规定传入实体的格式
	@POST
	@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
	public void createUser(User user) {
		
		userMap.put(user.getUserId(), user);
	}
	
	/**
	 * 删除
	 * @param id
	 */
	@DELETE
	@Path("{id}")
	public void deleteUser(@PathParam("id") String id) {
		
		userMap.remove(id);
	}
	
	/**
	 * 修改
	 * @param User
	 */
	@PUT
	@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
	public void updateUser(User user) {
		
		userMap.put(user.getUserId(), user);
	}
	
	/**
	 * 根据ID查询
	 * @param id
	 */
	@GET
	@Path("{id}")
	@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
	public User getUserById(@PathParam("id") String id) {
		
		return userMap.get(id);
	}
	
	/** 
	 * 查询所有 
	 * @return 
	 */  
	@GET 
	@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})  
	public List<User> getAllUsers(){ 
		
	    List<User> users = new ArrayList<User>();
	    User u1 = new User("001", "Pfff", "23");
	    User u2 = new User("002", "Jason", "32");
	    User u3 = new User("003", "Tom", "29");
	  	
	    userMap.put(u1.getUserId(), u1);
	    userMap.put(u2.getUserId(), u2);
	    userMap.put(u3.getUserId(), u3);
	  	
	    users.addAll(userMap.values());    
	    return users;  
	}  
}